const {
  $util,
} = getApp();
const MAX_LENGTH = 10;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    hasMore: true,
    loaded: false,
    list: [],
    abnorData: {
      imgSrc: '/common/static/images/abnor-16.png',
      text: '暂无收藏信息',
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(options);
    wx.setNavigationBarTitle({
      title: Number(options.collect) === 1 ? '我的收藏' : '浏览历史',
    });
    this.setData({
      collect: options.collect,
      'abnorData.text': Number(options.collect) === 1 ? '暂无收藏，点击 ☆ 收藏喜欢的内容' : '暂无浏览历史',
    });
  },
  onShow() {
    this.getList();
  },
  getList() {
    const { page } = this.data;
    let url = '';
    if (Number(this.data.collect) === 1) {
      url = 'entry/wxapp/information.news.collectlist';
    } else {
      url = 'entry/wxapp/information.news.history';
    }
    $util.request({
      url,
      data: {
        page,
      },
      success: (res) => {
        let list = res.data;
        if (page > 1) {
          list = [...this.data.list, ...list];
        }
        this.setData({
          list,
          hasMore: !(page > 1 && res.data.length < MAX_LENGTH),
          loaded: true,
          newsset: res.newsset,
        });
      },
    });
  },
  operateCollect(e) {
    let that = this;
    let { cid } = e.currentTarget.dataset;
    $util.request({
      url: 'entry/wxapp/information.news.newsCollect',
      data: {
        id: cid,
      },
      success: (res) => {
        setTimeout(() => {
          that.setData({
            page: 1,
            loaded: false,
          }, () => {
            that.getList();
          });
        }, 1500);
      },
      complete: () => {},
    });
  },

  delItem(e) {
    const { id, idx } = e.currentTarget.dataset;
    let url = '';
    if (Number(this.data.collect) === 1) {
      url = 'entry/wxapp/information.news.del_collect';
    } else {
      url = 'entry/wxapp/information.news.del_history';
    }
    $util.request({
      url,
      data: {
        id,
      },
      success: () => {
        const { list } = this.data;
        list.splice(idx, 1);
        this.setData({
          list,
        });
        wx.showToast({
          title: '删除成功',
          icon: 'none',
        });
      },
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.hasMore) return;
    this.setData({
      page: this.data.page + 1,
    }, () => {
      this.getList();
    });
  },

  go() {
    getApp().util.navigateTo('ws_party_const/pages/dynamic/index', {}, true);
  },
});
